<template>
  <page-wrap stay-still hide-tab title="交付服务">
    <view class="summary">
      <view class="summary-header">
        <text class="title">服务名称：</text>
        <text class="value">竞争力分析</text>
      </view>
      <view class="summary-form-wrap">
        <u-form
          class="summary-form"
          label-position="top"
          ref="uForm"
          :model="form"
          :error-type="['message']"
        >
          <block v-for="(item, index) in formList" :key="index">
            <view
              class="form-item-wrap"
              v-if="!item.baseOn || form[item.baseOn.prop] == item.baseOn.value"
              @click.capture="handleSelect(item, index)"
            >
              <u-form-item
                :class="{ pick: item.comp }"
                :label="item.label"
                :prop="item.prop"
              >
                <u-input
                  class="form-input"
                  v-model="form[item.prop]"
                  :disabled="!!item.comp"
                  :type="item.type"
                  :placeholder="item.inputPlaceholder"
                  :clearable="false"
                  @blur="handleSaveItem(item)"
                  @input="saveCurrentItem(item)"
                  :show-confirmbar="false"
                  :cursor-spacing="20"
                  maxlength="1000"
                />
                <!-- 下拉选择 -->
                <u-select
                  class="form-select"
                  v-model="item.show"
                  :list="item.data"
                  v-if="item.comp === 'select'"
                  @confirm="handleConfirm($event, item)"
                ></u-select>
              </u-form-item>
            </view>
          </block>
        </u-form>
      </view>
      <view class="operate-bar">
        <u-button
          class="save-btn"
          type="default"
          shape="circle"
          @click="handleSave"
          >返回</u-button
        >
        <u-button
          class="save-btn"
          type="primary"
          shape="circle"
          :loading="publishLoading"
          @click="handlePublish"
          >发布</u-button
        >
      </view>
    </view>
  </page-wrap>
</template>

<script>
import { uploadAction, uploadBaseUrl } from "@/api/index";
import {
  editServiceSummary,
  pubServiceSummary,
  viewServiceSummary,
} from "@/api/modules/career";
import RegionFilter from "@/components/RegionFilter";
import ShareMixin from "@/mixins/share";
export default {
  mixins: [ShareMixin],
  components: {
    RegionFilter,
  },
  data() {
    return {
      saveStatus: true,
      currentInputItem: {},
      // 编辑和新增的逻辑：后端服务使用dataType的形式来存储，并没有使用字段
      // 咨询数据类型 1问题类型 (多个逗号隔开) 2问题详情 3解决方案 4交付简历 5修改概述 6性格简析
      // 7工作优势 8工作盲点 9自诉现状 10发展诉求 11推荐职业1 12推荐职业2 13推荐职业3 14推荐理由1
      // 15推荐理由1 16推荐理由3 17用户姓名 18用户性别 19用户年龄
      personId: uni.getStorageSync("person-id").slice(2) || undefined,
      userInfo: {},
      form: {
        username: "",
        userSex: "",
        userAge: "",
        natureAnalyze: "",
        jobAdvantages: "",
        workBlindSpots: "",
        presentSituation: "",
        developmentDemands: "",
        solution: "",
        recommendJob1: "",
        recommendReason1: "",
        recommendJob2: "",
        recommendReason2: "",
        recommendJob3: "",
        recommendReason3: "",
      },
      formList: [
        {
          label: "用户姓名",
          prop: "username",
          inputPlaceholder: "请输入用户姓名",
          type: "text",
          dataType: 17,
          orderNum: 1,
        },
        {
          label: "用户年龄",
          prop: "userAge",
          inputPlaceholder: "请输入用户年龄",
          type: "text",
          dataType: 19,
          orderNum: 2,
        },
        {
          label: "用户性别",
          prop: "userSex",
          inputPlaceholder: "请选择用户性别",
          comp: "select",
          dataType: 18,
          orderNum: 3,
          data: [
            {
              label: "男",
              value: "男",
            },
            {
              label: "女",
              value: "女",
            },
          ],
          show: false,
        },
        {
          label: "性格简析",
          prop: "natureAnalyze",
          inputPlaceholder: "请输入性格简析",
          type: "textarea",
          dataType: 6,
          orderNum: 4,
        },
        {
          label: "工作优势",
          prop: "jobAdvantages",
          inputPlaceholder: "请输入工作优势",
          type: "textarea",
          dataType: 7,
          orderNum: 5,
        },
        {
          label: "工作盲点",
          prop: "workBlindSpots",
          inputPlaceholder: "请输入工作盲点",
          type: "textarea",
          dataType: 8,
          orderNum: 6,
        },
        {
          label: "自述现状",
          prop: "presentSituation",
          inputPlaceholder: "请上传自述现状",
          type: "textarea",
          dataType: 9,
          orderNum: 7,
        },
        {
          label: "发展诉求",
          prop: "developmentDemands",
          inputPlaceholder: "请发展诉求",
          type: "textarea",
          dataType: 10,
          orderNum: 8,
        },
        {
          label: "解决方案",
          prop: "solution",
          inputPlaceholder: "请输入解决方案",
          type: "textarea",
          dataType: 3,
          orderNum: 9,
        },
        {
          label: "推荐职业1",
          prop: "recommendJob1",
          inputPlaceholder: "请输入推荐职业1",
          comp: "search",
          dataType: 11,
          orderNum: 10,
        },
        {
          label: "推荐理由1",
          prop: "recommendReason1",
          inputPlaceholder: "请输入推荐理由1",
          type: "textarea",
          dataType: 14,
          orderNum: 11,
        },
        {
          label: "推荐职业2",
          prop: "recommendJob2",
          inputPlaceholder: "请输入推荐职业2",
          comp: "search",
          dataType: 12,
          orderNum: 12,
        },
        {
          label: "推荐理由2",
          prop: "recommendReason2",
          inputPlaceholder: "请输入推荐理由2",
          type: "textarea",
          dataType: 15,
          orderNum: 13,
        },
        {
          label: "推荐职业3",
          prop: "recommendJob3",
          inputPlaceholder: "请输入推荐职业3",
          comp: "search",
          dataType: 13,
          orderNum: 14,
        },
        {
          label: "推荐理由3",
          prop: "recommendReason3",
          inputPlaceholder: "请输入推荐理由3",
          type: "textarea",
          dataType: 16,
          orderNum: 15,
        },
      ],
      rules: {
        username: [
          {
            required: true,
            message: "请输入用户姓名",
            trigger: ["change", "blur"],
          },
        ],
        userAge: [
          {
            required: true,
            message: "请输用户年龄",
            trigger: ["change", "blur"],
          },
        ],
        userSex: [
          {
            required: true,
            message: "请输入用户性别",
            trigger: ["change", "blur"],
          },
        ],
        natureAnalyze: [
          {
            required: true,
            message: "请输入性格简析",
            trigger: ["change", "blur"],
          },
        ],
        jobAdvantages: [
          {
            required: true,
            message: "请输入工作优势",
            trigger: ["change", "blur"],
          },
        ],
        workBlindSpots: [
          {
            required: true,
            message: "请输入工作盲点",
            trigger: ["change", "blur"],
          },
        ],
        presentSituation: [
          {
            required: true,
            message: "请输入自述现状",
            trigger: ["change", "blur"],
          },
        ],
        developmentDemands: [
          {
            required: true,
            message: "请输入发展诉求",
            trigger: ["change", "blur"],
          },
        ],
        solution: [
          {
            required: true,
            message: "请输入解决方案",
            trigger: ["change", "blur"],
          },
        ],
        recommendJob1: [
          {
            required: true,
            message: "请选择推荐职业1",
            trigger: ["change", "blur"],
          },
        ],
        recommendReason1: [
          {
            required: true,
            message: "请输入推荐理由1",
            trigger: ["change", "blur"],
          },
        ],
        recommendJob2: [
          {
            required: true,
            message: "请选择推荐职业2",
            trigger: ["change", "blur"],
          },
        ],
        recommendReason2: [
          {
            required: true,
            message: "请输入推荐理由2",
            trigger: ["change", "blur"],
          },
        ],
        recommendJob3: [
          {
            required: true,
            message: "请选择推荐职业3",
            trigger: ["change", "blur"],
          },
        ],
        recommendReason3: [
          {
            required: true,
            message: "请输入推荐理由3",
            trigger: ["change", "blur"],
          },
        ],
      },
      publishLoading: false,
      isUploaded: false,
      resumeList: [],
      id: "",
      serviceId: "",
      serviceRecordId: "",
      currentProp: "",
      keyIdMap: new Map(),
    };
  },
  watch: {
    userInfo: {
      handler(val) {
        this.form = {
          username: val.username,
          userSex: val.userSex,
          userAge: val.userAge,
          optimization: val.optimization,
          optimizedResume: val.optimizedResume,
          natureAnalyze: val.natureAnalyze,
          jobAdvantages: val.jobAdvantages,
          workBlindSpots: val.workBlindSpots,
          presentSituation: val.presentSituation,
          developmentDemands: val.developmentDemands,
          solution: val.solution,
          recommendReason1: val.recommendReason1,
          recommendReason2: val.recommendReason2,
          recommendReason3: val.recommendReason3,
        };
      },
      immediate: true,
    },
  },
  onLoad(opt) {
    this.serviceId = opt.serviceId || "";
    this.serviceRecordId = opt.serviceRecordId || "";
    this.currentProp = opt.str || "";
  },
  onShow() {
    this.getReport();
  },
  mounted() {
    this.viewServiceSummaryFn();
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  methods: {
    saveCurrentItem(item) {
      console.log("item", item);
      this.saveStatus = false;
      this.currentInputItem = {
        serviceId: this.serviceId,
        serviceRecordId: this.serviceRecordId,
        dataType: item.dataType,
        content: this.form[item.prop],
        orderNum: item.orderNum,
      };
    },
    handleSaveItem(item) {
      if (!this.form[item.prop] && !this.serviceId) {
        // 没有请求过又不是编辑，就return
        return;
      }
      const params = {
        serviceId: this.serviceId,
        serviceRecordId: this.serviceRecordId,
        dataType: item.dataType,
        content: this.form[item.prop],
        orderNum: item.orderNum,
      };
      if (this.keyIdMap.get(item.dataType)) {
        params.id = this.keyIdMap.get(item.dataType);
      }
      this.editServiceSummaryFn(params);
    },
    editServiceSummaryFn(params) {
      this.saveStatus = true;
      editServiceSummary(params).then((res) => {
        if (res.code !== 200) {
          uni.showToast({ icon: "none", title: res.status_desc });
        } else {
          if (!this.keyIdMap.get(res.data)) {
            // 编辑过后如果没有主键id的话就保存起来
            this.keyIdMap.set(params.dataType, res.data.id);
          }
          // uni.showToast({ icon: "none", title: "已保存当前更改" });
        }
      });
    },
    viewServiceSummaryFn() {
      const params = {
        serviceRecordId: this.serviceRecordId,
        serviceId: this.serviceId,
      };
      viewServiceSummary(params).then((res) => {
        if (res.code == 200 && Array.isArray(res.data) && res.data.length) {
          res.data.forEach((item) => {
            this.keyIdMap.set(item.dataType, item.id); // 保存每一项的主键id，用作编辑
            if (item.dataType == 3) {
              this.form.solution = item.content;
            }
            if (item.dataType == 17) {
              this.form.username = item.content;
            }
            if (item.dataType == 18) {
              this.form.userSex = item.content;
            }
            if (item.dataType == 19) {
              this.form.userAge = item.content;
            }
            if (item.dataType == 6) {
              this.form.natureAnalyze = item.content;
            }
            if (item.dataType == 7) {
              this.form.jobAdvantages = item.content;
            }
            if (item.dataType == 8) {
              this.form.workBlindSpots = item.content;
            }
            if (item.dataType == 9) {
              this.form.presentSituation = item.content;
            }
            if (item.dataType == 10) {
              this.form.developmentDemands = item.content;
            }
            if (item.dataType == 11) {
              this.form.recommendJob1 = item.content
                ? JSON.parse(item.content).activityName
                : ""; // TODO： 这三份报告还不知道是啥格式
            }
            if (item.dataType == 12) {
              this.form.recommendJob2 = item.content
                ? JSON.parse(item.content).activityName
                : "";
            }
            if (item.dataType == 13) {
              this.form.recommendJob3 = item.content
                ? JSON.parse(item.content).activityName
                : "";
            }
            if (item.dataType == 14) {
              this.form.recommendReason1 = item.content;
            }
            if (item.dataType == 15) {
              this.form.recommendReason2 = item.content;
            }
            if (item.dataType == 16) {
              this.form.recommendReason3 = item.content;
            }
          });
        }
      });
    },
    getNowTime() {
      let now = new Date();
      let year = now.getFullYear(); //获取完整的年份(4位,1970-????)
      let month = now.getMonth() + 1; //获取当前月份(0-11,0代表1月)
      let today = now.getDate(); //获取当前日(1-31)
      let hour = now.getHours(); //获取当前小时数(0-23)
      let minute = now.getMinutes(); //获取当前分钟数(0-59)
      let second = now.getSeconds(); //获取当前秒数(0-59)
      let nowTime = "";
      nowTime =
        year +
        "-" +
        this.fillZero(month) +
        "-" +
        this.fillZero(today) +
        " " +
        this.fillZero(hour) +
        ":" +
        this.fillZero(minute) +
        ":" +
        this.fillZero(second);
      return nowTime;
    },

    fillZero(str) {
      let realNum;
      if (str < 10) {
        realNum = "0" + str;
      } else {
        realNum = str;
      }
      return realNum;
    },
    getReport() {
      // 这段逻辑是为了从选择报告后跳转回来获取报告的
      if (this.currentProp) {
        this.form[this.currentProp] =
          getApp().globalData[this.currentProp].activityName;
        const currentPropValue = {
          activityId: getApp().globalData[this.currentProp].activityId,
          activityName: getApp().globalData[this.currentProp].activityName,
          activityIdCode: getApp().globalData[this.currentProp].activityIdCode,
          activityTypeCode:
            getApp().globalData[this.currentProp].activityTypeCode,
          createdTime: this.getNowTime(),
        };
        // 保存报
        const params = {
          serviceRecordId: this.serviceRecordId,
          serviceId: this.serviceId,
          dataType:
            this.currentProp == "recommendJob1"
              ? 11
              : this.currentProp == "recommendJob2"
              ? 12
              : 13,
          content: JSON.stringify(currentPropValue),
          orderNum:
            this.currentProp == "recommendJob1"
              ? 10
              : this.currentProp == "recommendJob2"
              ? 12
              : 14,
        };
        this.editServiceSummaryFn(params);
      }
    },
    // 选择本地文件
    handleUpload() {
      // #ifdef H5
      let uploadApi = uni.chooseFile;
      // #endif
      // #ifdef MP-WEIXIN
      let uploadApi = wx.chooseMessageFile;
      // #endif
      const TYPE = [".doc", ".docx", ".png", ".jpg", ".jepg", ".png", ".pdf"];
      uploadApi({
        count: 1,
        extension: TYPE,
        success: (res) => {
          let tempFilePaths = res.tempFiles;
          let fileExt = "." + tempFilePaths[0].name.replace(/.+\./, "");
          if (TYPE.indexOf(fileExt) < 0) {
            return uni.showToast({
              icon: "none",
              title: "文件类型错误",
            });
          }
          if (tempFilePaths[0].size / (1024 * 1024) > 10) {
            return uni.showToast({
              icon: "none",
              title: "文件大小不能超过10M",
            });
          }
          uni.showLoading({
            title: "正在上传",
          });
          uni.uploadFile({
            url: uploadAction,
            filePath: tempFilePaths[0].path,
            name: "file",
            success: (uploadRes) => {
              uni.showToast({
                icon: "none",
                title: "上传成功",
              });
              let name = tempFilePaths[0].name;
              if (name.length > 10) {
                name = name.slice(0, 10) + "...";
              }
              let info = {
                resume: uploadBaseUrl + uploadRes.data,
                resumeName: tempFilePaths[0].name,
                resumeSimpleName: name,
              };
              this.form.optimizedResume = info.resumeName;
              this.resumeList = info;
              this.isUploaded = true;
            },
          });
        },
      });
    },
    handleSelect(item) {
      console.log(item.prop, "item.prop");
      if (item.upload) {
        this.handleUpload();
        return;
      }
      if (item.comp == "select") {
        this.$set(item, "show", true);
        return;
      }
      if (item.comp == "search") {
        this.currentProp = item.prop;
        uni.navigateTo({
          url: `/pagesSub/library/search/index?from=deliveryCompetitivenessService&str=${item.prop}&serviceId=${this.serviceId}&serviceRecordId=${this.serviceRecordId}`,
        });
      }
    },
    handleConfirm(e, item) {
      if (Array.isArray(e)) {
        this.$set(this.form, item.prop, e[0].label);
        if (item.propVal) {
          this.$set(this.form, item.propVal, e[0].value);
        }
      } else {
        let time = `${e.year}-${e.month}-${e.day}`;
        this.$set(this.form, item.prop, time);
      }
      setTimeout(() => {
        this.$refs.uForm.validate();
        const params = {
          serviceRecordId: this.serviceRecordId,
          serviceId: this.serviceId,
          dataType: item.dataType,
          content: this.form[item.prop],
        };
        if (this.keyIdMap.get(item.dataType)) {
          params.id = this.keyIdMap.get(item.dataType);
        }
        this.editServiceSummaryFn(params);
      }, 0);
    },
    handlePublish() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          this.publishLoading = true;
          const params = {
            serviceRecordId: this.serviceRecordId,
            serviceId: this.serviceId,
          };
          pubServiceSummary(params)
            .then((res) => {
              if (res.code == 200) {
                uni.showToast({ icon: "none", title: "发布成功！" });
                this.handleSave();
              }
            })
            .finally(() => {
              this.publishLoading = false;
            });
        } else {
          uni.showToast({ icon: "none", title: "请完善信息后再发布！" });
        }
      });
    },
    handleSave() {
      //退出的时候保存当前编辑内容
      if (!this.saveStatus) {
        this.editServiceSummaryFn(this.currentInputItem);
      }
      uni.reLaunch({
        url: `/pagesSub/userCenter/serviceRecord/index`,
      });
      // uni.navigateBack({
      //   delta: 1,
      // });
    },
  },
};
</script>

<style lang="scss" scoped>
.summary {
  // flex-grow: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 32rpx 32rpx 360rpx;
  box-sizing: border-box;
  position: relative;
  padding-bottom: 120rpx;
  &-header {
    font-size: 32rpx;
    padding: 0 0 24rpx 32rpx;
    color: #333;
    font-weight: 600;
    .title {
      margin-right: 12rpx;
      color: #666;
    }
    .value {
      color: #555;
    }
  }
  .summary-form-wrap {
    flex-grow: 1;
    background: #fff;
    padding-top: 32rpx;
    border-radius: 16rpx;
    ::v-deep .u-form {
      padding: 0 32rpx;
      background: $uni-bg-color;
      border-radius: 24rpx;
      .u-form-item {
        .btn-group {
          padding: 0 24rpx;
          line-height: 102rpx;
          .cancel,
          .confirm {
            padding: 0 16rpx;
          }
        }
      }
    }
  }
  .operate-bar {
    display: flex;
    justify-content: space-evenly;
    width: 100%;
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 99;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
    .save-btn {
      flex-shrink: 0;
      margin: 82rpx 0 4rpx;
      width: 40%;
    }
  }
}
::v-deep .u-input__textarea {
  min-height: 80rpx !important;
}
::v-deep .u-input input {
  font-size: 28rpx !important;
}
::v-deep .u-btn--default {
  color: #fff !important;
  border-color: #c0c4cc;
  background-color: #c0c4cc !important;
}
</style>
